<template>
  <div class="login-container">
    <div class="login-box">
      <h2>{{ $route.meta.title }}</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label>用户名</label>
          <input type="text" v-model="form.username" required />
        </div>
        <div class="form-group">
          <label>密码</label>
          <input type="password" v-model="form.password" required />
        </div>
        <button type="submit">登录</button>
        <p>
          还没有账号? <router-link to="/register">立即注册</router-link>
        </p>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user' // ✅ 引入 Pinia 的 user store
import axios from 'axios'


const router = useRouter()
const route = useRoute()
const userStore = useUserStore() // ✅ 初始化 Pinia 的 store

const form = ref({
  username: '',
  password: ''
})

const handleLogin = async () => {
  try {
    const res = await axios.post('/api/login', {
      userName: form.value.username,
      password: form.value.password
    })

    const user = res.data
    userStore.setUser(user)
    
    const redirect = route.query.redirect || { name: 'HomeView' }
    console.log('跳转目标:', redirect, typeof redirect)
    router.push(redirect)
  } catch (err) {
    console.error(err.response)
    alert(err.response?.data || '登录失败')
  }
}

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-box {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  width: 350px;
}

h2 {
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  margin-top: 10px;
}

button:hover {
  background-color: #0b7dda;
}

p {
  margin-top: 15px;
  font-size: 14px;
}

router-link {
  color: #2196F3;
  text-decoration: none;
}

router-link:hover {
  text-decoration: underline;
}
</style>